package com.cyber.app_container.exception;

import com.cyber.app_container.dto.Response;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 全局异常处理（将异常转换为结构化的错误响应）
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Response handleBusinessException(BusinessException ex) {
        return Response.builder().code(ex.getCode()).
                message(ex.getMessage()).
                data(ex.getDetails()).success(false).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleValidationException(MethodArgumentNotValidException ex) {
        List<String> errorMessages = ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .toList();
        ErrorCode errorCode;
         if (errorMessages.size() == 1) {
             errorCode = ErrorCode.fromCode(errorMessages.getFirst());
        } else {
            errorCode = ErrorCode.INVALID_PARAM;
        }
        return Response.error(errorCode);
    }

    @ExceptionHandler(Exception.class)
    public Response handleException(Exception ex) {
        Map<String, Object> details = new HashMap<>();
        details.put("error", ex.getClass().getSimpleName());
        details.put("msg", ex.getMessage());

        return Response.builder().code(ErrorCode.SYSTEM_ERROR.getCode()).
                message(ErrorCode.SYSTEM_ERROR.getMessage()).
                data(details).success(false).build();
    }
}
